using System;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;

namespace Lombiq.HelpfulLibraries.Common.Utilities;

public static class Sha256Helper
{
    private static readonly Lazy<string> EmptyLazy = new(() => ComputeHash(string.Empty));

    /// <summary>
    /// 从指定的 <paramref name="text"/> 字符串计算 SHA-256 强（加密）哈希。
    /// </summary>
    /// <param name="text">使用 <see cref="Encoding.UTF8"/> 解码为可哈希字节数组的文本。</param>
    /// <returns>SHA-256 哈希的十六进制字符串表示。</returns>
    public static string ComputeHash(string text)
    {
        var hashedIdBytes = SHA256.HashData(Encoding.UTF8.GetBytes(text));

        var stringBuilder = new StringBuilder();

        foreach (var hashedIdByte in hashedIdBytes)
        {
            stringBuilder.Append(hashedIdByte.ToString("x2", CultureInfo.InvariantCulture));
        }

        return stringBuilder.ToString();
    }

    public static string Empty() => EmptyLazy.Value;
}
